<?php
namespace Views;
/**
 * File holds class for generating account view (sign in, sign up, edit user
 * details etcetera
 *
 * PHP version 5.3.5
 *
 * @category   CM
 * @package    Views
 * @subpackage -
 * @author     markus karileet <markuskarileet@hotmail.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @link       -
 */
class Account extends Page {
    /**
     * Account service variable
     * @var \Services\Account
     */
	private $_service;
	
	/**
	 * Constructor initiates super setUp method and appropriate service class
	 */
	public function __construct() {
		$this->setUp();
		$this->_service = new \Services\Account();
	}
	
	/**
	 * Method logs user in the application. When login is unsuccessful, message
	 * is shown and user is redirected to sign in page. When successful, user
	 * is redirected to ones companys analytics page. When exception occurs, 
	 * user is redirected to welcome page and general error is shown
	 * @param array $post HTTP POST array
	 */
	public function login($post) {
	    //try to login user
	    try {
		    $user = $this->_service->authenticate($post);
		    if (!$user) {
		        //when user login failed, show login page
		        $this->setMessage(array('error' => $this->_translation['loginFailed']));
		        $this->displayStatic('signin.tpl');
		        //when login successful, show business analytics page OR welcome page
		        //when user has no related businesses
		    } else {
		        $template = new \Entities\Business();
		        $template->setAccount($user->getId());
		        $business = $this->_service->select($template);
		        $businessView = new Business();
		        $businessView->setMessage(array('success' => $this->_translation['loginSuccess']));
		        if ($business) {
		            $businessView->viewMyAnalytics($business->getId());
		        } else {
		            $businessView->displayStatic('welcome.tpl');
		        }
		    }
	    } catch (\Exception $e) {
	        //notify user that something is wrong!
	        $this->_pagePanic();
	    }
	}
	
	/**
	 * Method logs user out by clearing session and template variables as well
	 * as reloads menus
	 */
	public function logout() {
		$this->_service->clearUserData();
		$this->_messages = array('success' => $this->_translation['logoutSuccess']);
		//reset menus with setup
	 	$this->_smarty->assign('company', false);
	 	$this->_smarty->assign('loggedUser', false);
	 	$this->setUp();
		$this->displayStatic('welcome.tpl');
	}
	
	/**
	 * Method shows registration form. When DB connection fails, then user is 
	 * redirected to pagePanic page
	 */
	public function viewRegistraitionForm() {
		$categoryService = new \Services\Type();
		$cat = array();
		try {
    		$types = $categoryService->getAllTypes();
    		//translate categorys for dropdown
    		foreach (array_keys($types) as $key) {
    			$l = $this->_translation[$types[$key]->getName()];
    			$cat[$types[$key]->getId()] = $l;
    		}
    		$this->_smarty->assign('cats', $cat);
    		$this->displayStatic('registration.tpl');
		} catch (\Exception $e) {
		    //notify user that something is wrong!
	        $this->_pagePanic();
		}
		
	}
	
	/**
	 * Method tries to register a new user with a new company. When register is
	 * successful, user is logged in. When DB exception occurrs, user is redirected
	 * to pagePanic page
	 * @param array $post HTTP POST array
	 */
	public function register($post) {
		//insert account
		try {
    		if ($this->_service->prepareInsert($post) > 0) {
    			$message = array('success' => $this->_translation['registrationSuccess']);
    		} else {
    			$message = array('error' => $this->_translation['registrationFail']);
    		}
    		
    		//log user in as well :)
    		$this->_service->authenticate($post);
    		
    		$this->setMessage($message);
    		$this->viewRegistrationDetails();
		} catch (\Exception $e) {
		    //notify user that something is wrong!
		    $this->_pagePanic();
		}
	}
	
	/**
	 * Method shows registration details after user is signed up and logging 
	 * in was successful. It also redraws left menu
	 */
	public function viewRegistrationDetails() {
		$this->setUp();
		$this->displayStatic('registrationSuccess.tpl');
	}
	
	/**
	 * Method shows user account editing form. Upon DB exception, user is redirected
	 * to pagePanic
	 * @param int $id Account ID to edit
	 */
	public function viewEditForm($id) {
		if ($this->_loggedInUser->getId() == $id || $this->_loggedInUser->getType() == \Enum\AccountType::Admin) {
		    try {
    			$template = new \Entities\Account();
    			$template->setId($id);
    			$account = $this->_service->select($template);
    			$this->_smarty->assign('account', $account);
    			$business = new \Entities\Business();
    			$business->setAccount($account->getId());
    			$businesses = $this->_service->selectMulti($business);
    			$bService = new \Services\Business();
    			$this->_smarty->assign('nps', $bService->getNpsScores($businesses));
    			$this->_smarty->assign('businesses', $businesses);
    			$this->displayStatic('userEdit.tpl');
		    } catch (\Exception $e) {
		        //notify user that something is wrong!
		        $this->_pagePanic();
		    }
		} else {
			$this->_toLoginPage();
		}
	}
	
	/**
	 * Method updates account data. User is redirected to edit page. DB exception
	 * leads to pagePanic
	 * @param array $post HTTP POST array
	 */
	public function update($post) {
		//since admin can update any user, read user from database when
		//admin is updating. otherwise its logged in user stuff
		try {
    		if ($this->_loggedInUser->getType() == \Enum\AccountType::Admin){
    			$object = new \Entities\Account();
    			$object->setId((int)$post['account']);
    			$user = $this->_service->select($object);
    		} else {
    			//just to be on the safe side, authenticate! no hacks allowed
    			$user = $this->_service->authenticate($post);
    		}
    		if ($this->_service->prepareUpdate($post, $user) > 0) {
    			$message = array('success' => "Edit successful");
    		} else {
    			$message = array('error' => "Problem storing edit");
    		}
    		$this->setMessage($message);
    		$this->viewEditForm((int)$post['account']);
		} catch (\Exception $e) {
		    //notify user that something is wrong!
		    $this->_pagePanic();
		}
	}
	
	/**
	 * Method shows user admin page
	 */
	public function viewUsers() {
		try {
			if ($this->_loggedInUser->getType() == \Enum\AccountType::Admin){
				$this->_smarty->assign('accounts', $this->_service->getAll());
				$this->displayStatic('userList.tpl');
			} else {
				$this->_toLoginPage();
			}
		} catch (\Exception $e) {
			//notify user that something is wrong!
			$this->_pagePanic($e->getMessage());
		}	
	}
}